import time
import traceback
import logging
import os

from info_config import dbname
from info_config import prometheus_url
from info_config import invalid_index_prometheus_metrics_name
from info_config import con_timeout

from tool_util import prometheus_push
from tool_util import create_conn
from tool_util import get_pg_invalid_index
from tool_util import get_resource_info
from tool_util import get_all_databases

pg_client_addr_global = {}

# Get the current script path
script_path = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_path, "invalid_index_monitor.log")

logging.basicConfig(
    filename=log_file,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


def invalid_index_monitor(pg_info):
    id = pg_info[0]
    name = pg_info[1]
    pg_host = pg_info[2].get("host")
    pg_port = pg_info[2].get("port")
    default_conn = create_conn(pg_host, pg_port, dbname, timeout=con_timeout)
    if default_conn is None:
        return
    databases = get_all_databases(default_conn)
    default_conn.close()
    for db in databases:
        try:
            db1 = db[0]
            conn = create_conn(pg_host, pg_port, db1, timeout=con_timeout)
            invalid_index = get_pg_invalid_index(conn)
            if invalid_index is not None:
                for i in invalid_index:
                    indexName = i[1]
                    logging.info(f"invalid index found in {db1} {indexName} ")
                    metric_data = f'{invalid_index_prometheus_metrics_name}{{instanceId="{id}" ,resourceName="{name}",db="{db1}" ,indexName = "{indexName}"}} 0'
                    prometheus_push(prometheus_url, metric_data)
        except Exception as e:
            traceback.print_exc()

def invalid_index_monitor_all(pg_info_list):
    for pg_info in pg_info_list:
        try:
            logging.info(f"start monitor {pg_info}")
            invalid_index_monitor(pg_info)
        except Exception as e:
            traceback.print_exc()


def main():
    pg_info_list = get_resource_info()
    invalid_index_monitor_all(pg_info_list)


if __name__ == "__main__":
    main()
